# coding: utf-8

# 使用py2.7，运行在内网服务器上，定时上传录音

import datetime
import time
import json
import requests

# 开发使用URl
PENDING_AUDIO_URL = 'http://127.0.0.1:5000/outbound/audio/pending_list'
BASE_UPLOAD_AUDIO_URL = 'http://127.0.0.1:5000/outbound/audio/upload/{local_call_id}'

# 线上使用URL
#PENDING_AUDIO_URL = 'http://opc.wanpinghui.com/outbound/audio/pending_list'
#BASE_UPLOAD_AUDIO_URL = 'http://opc.wanpinghui.com/outbound/audio/upload/{local_call_id}'

while True:
    try:
        response = requests.get(PENDING_AUDIO_URL)
        result = response.content.decode('utf-8')
        result = json.loads(result)

        for i in result:
            base_audio_path = i['audio_path']
            local_call_id = i['local_call_id']
            mobile = i['mobile']

            # 通过url下载录音文件
            audio_path = base_audio_path.replace('\\', '/')
            # http://192.168.1.207:8080/Record/20170815/004/141457_1_18903718031_18900000000.wav
            audio_path = 'http://192.168.1.207:8080/Record/' + audio_path + '.wav'
            audio_file_name = audio_path.split('/')[-1]

            tmp_audio_response = requests.get(audio_path)
            #print tmp_audio_response.content
            with open('tmp_audio.wav', 'w') as f:
                f.write(tmp_audio_response.content)

            # 上传录音
            upload_audio_url = BASE_UPLOAD_AUDIO_URL.format(local_call_id=local_call_id)
            upload_files = {
                'upload_file': (audio_file_name, open('tmp_audio.wav', 'rb'))
            }
            r = requests.post(upload_audio_url, files=upload_files)
            print(r.text)
    except Exception as e:
        print(e)

    time.sleep(10)
    print("run at: %s" % datetime.datetime.now())
